<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>评论</p>
    </header>
    
    <!-- 评论区部分 -->
    <div class="remark-container">
      <ul class="remark-list">
        <li v-for="item in remarkArr" :key="item.id" class="remark-item">
          <div class="remark-user">
            <img :src="item.user?.userImg || defaultUserImg" @error="handleUserImageError">
            <div class="user-info">
              <span class="username">{{item.user?.username || '匿名用户'}}</span>
              <span class="remark-date">{{formatDate(item.remarkDate)}}</span>
            </div>
            <div class="remark-actions">
              <!-- 删除按钮 - 悬停显示 -->
              <button 
                v-if="user && user.userId === item.user?.id"
                @click="showDeleteConfirm(item.id)"
                class="btn-delete"
                :title="'删除这条评论'"
                :disabled="isDeleting === item.id">
                <i class="fa" :class="isDeleting === item.id ? 'fa-spinner fa-spin' : 'fa-trash'"></i>
                <span class="btn-text">{{ isDeleting === item.id ? '删除中...' : '删除' }}</span>
              </button>
              
            </div>
          </div>
          <div class="remark-content">
            <!-- 编辑模式 -->
            <div v-if="editingRemarkId === item.id" class="edit-mode">
              <textarea v-model="editText" rows="3" placeholder="请输入评论内容..."></textarea>
              <div class="edit-actions">
                <button @click="saveEdit(item.id)" class="btn-save" :disabled="!editText.trim()">
                  <i class="fa fa-check"></i> 保存
                </button>
                <button @click="cancelEdit" class="btn-cancel">
                  <i class="fa fa-times"></i> 取消
                </button>
              </div>
            </div>
            <!-- 显示模式 -->
            <p v-else>{{item.remark || '暂无评价内容'}}</p>
          </div>
        </li>
      </ul>
      
      <div v-if="remarkArr.length === 0" class="no-remarks">
        <i class="fa fa-comments"></i>
        <p>暂无评价</p>
      </div>
    </div>

    <!-- 发表评论部分 -->
    <div class="remark-input">
      <input 
        type="text" 
        v-model="remarkText" 
        placeholder="请输入您的评论..."
        @keyup.enter="submitRemark">
      <button @click="submitRemark" :disabled="!remarkText || isSubmitting">
        <i class="fa" :class="isSubmitting ? 'fa-spinner fa-spin' : 'fa-paper-plane'"></i>
        <span class="btn-text">{{ isSubmitting ? '提交中...' : '发表' }}</span>
      </button>
    </div>
    
    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="hideDeleteModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <i class="fa fa-times" @click="hideDeleteModal"></i>
        </div>
        <div class="modal-body">
          <p>确定要删除这条评论吗？此操作不可撤销。</p>
        </div>
        <div class="modal-footer">
          <button @click="hideDeleteModal" class="btn-cancel">取消</button>
          <button @click="confirmDelete" class="btn-confirm" :disabled="isDeleting">
            <i v-if="isDeleting" class="fa fa-spinner fa-spin"></i>
            {{ isDeleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 底部部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'RemarkPage',
  components: {
    Footer
  },
  
  data() {
    return {
      businessId: this.$route.query.businessId,
      remarkText: '',
      remarkArr: [],
      user: {},
      isSubmitting: false,
      isDeleting: null, // 记录正在删除的评论ID
      editingRemarkId: null, // 记录正在编辑的评论ID
      editText: '', // 编辑文本
      showDeleteModal: false, // 删除确认弹窗
      deleteRemarkId: null, // 待删除的评论ID
      defaultUserImg: require('../assets/default-user.png')
    }
  },
  async created() {
    this.user = this.$getSessionStorage('user');
    await this.fetchRemarks();
  },
  methods: {
    // 格式化日期（使用原生JavaScript替代moment）
    formatDate(dateString) {
      if (!dateString) return '未知时间';
      
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '无效日期';
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '日期错误';
      }
    },
    
    // 获取评论列表
    async fetchRemarks() {
      try {
        const response = await this.$axios.get(`/api/remarks/business/${this.businessId}`);
        
        if (response.data.success) {
          this.remarkArr = response.data.data || [];
		  
        } else {
          console.error('获取评论失败:', response.data.message);
          this.remarkArr = [];
        }
      } catch (error) {
        console.error('获取评论失败:', error);
        this.remarkArr = [];
      }
    },
    
    // 提交评论
    async submitRemark() {
      if (!this.remarkText.trim()) {
        alert('评论内容不能为空');
        return;
      }
      
      if (!this.user?.userId) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }
      
      this.isSubmitting = true;
      
      try {
		const token=this.user.token;
        const remarkData = {
          remark: this.remarkText,
          user: {
            id: this.user.userId,
            username: this.user.username
          },
          business: {
            id: this.businessId
          },
          remarkDate: new Date().toISOString()
        };
        const response = await this.$axios.post('/api/remarks', remarkData);
        
        if (response.data.success) {
          this.remarkText = '';
          await this.fetchRemarks();
		  console.log(remarkData);
          this.showSuccessMessage('评论成功');
        } else {
          this.showErrorMessage('评论失败: ' + (response.data.message || ''));
        }
      } catch (error) {
        console.error('评论失败:', error);
        this.showErrorMessage('评论失败，请稍后再试');
      } finally {
        this.isSubmitting = false;
      }
    },
    
    // 显示删除确认弹窗
    showDeleteConfirm(remarkId) {
      this.deleteRemarkId = remarkId;
      this.showDeleteModal = true;
    },
    
    // 隐藏删除确认弹窗
    hideDeleteModal() {
      this.showDeleteModal = false;
      this.deleteRemarkId = null;
    },
    
    // 确认删除评论
    async confirmDelete() {
      if (!this.deleteRemarkId) return;
      
      this.isDeleting = this.deleteRemarkId;
      
      try {
        const response = await this.$axios.delete(`/api/remarks/user/${this.user.userId}/remark/${this.deleteRemarkId}`);
        
        if (response.data.success) {
          await this.fetchRemarks();
          this.showSuccessMessage('删除成功');
          this.hideDeleteModal();
        } else {
          this.showErrorMessage('删除失败: ' + (response.data.message || ''));
        }
      } catch (error) {
        console.error('删除评论失败:', error);
        this.showErrorMessage('删除失败，请稍后再试');
      } finally {
        this.isDeleting = null;
      }
    },
    
    // 编辑评论
    editRemark(item) {
      this.editingRemarkId = item.id;
      this.editText = item.remark || '';
    },
    
    // 保存编辑
    async saveEdit(remarkId) {
      if (!this.editText.trim()) {
        alert('评论内容不能为空');
        return;
      }
      
      try {
        const response = await this.$axios.put(`/api/remarks/${remarkId}`, {
          remark: this.editText
        });
        
        if (response.data.success) {
          await this.fetchRemarks();
          this.cancelEdit();
          this.showSuccessMessage('编辑成功');
        } else {
          this.showErrorMessage('编辑失败: ' + (response.data.message || ''));
        }
      } catch (error) {
        console.error('编辑评论失败:', error);
        this.showErrorMessage('编辑失败，请稍后再试');
      }
    },
    
    // 取消编辑
    cancelEdit() {
      this.editingRemarkId = null;
      this.editText = '';
    },
    
    // 显示成功消息
    showSuccessMessage(message) {
      // 可以使用更优雅的提示方式，如 Toast 组件
      alert(message);
    },
    
    // 显示错误消息
    showErrorMessage(message) {
      alert(message);
    },
    
    // 处理用户图片加载错误
    handleUserImageError(e) {
      e.target.src = this.defaultUserImg;
    }
  }
}
</script>

<style scoped>
  /* 总容器 */
  .wrapper {
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
  }

  /* header部分 */
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /* 评论容器 */
  .remark-container {
    width: 100%;
    margin-top: 12vw;
    margin-bottom: 14vw;
    padding: 2vw;
    box-sizing: border-box;
  }

  /* 评论列表 */
  .remark-list {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  /* 评论项 */
  .remark-item {
    background-color: #fff;
    border-radius: 8px;
    padding: 3vw;
    margin-bottom: 3vw;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }

  .remark-item:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  /* 评论用户信息 */
  .remark-user {
    display: flex;
    align-items: center;
    margin-bottom: 2vw;
    justify-content: space-between;
  }

  .remark-user img {
    width: 10vw;
    height: 10vw;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 2vw;
  }

  .user-info {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .username {
    font-size: 3.8vw;
    font-weight: bold;
    color: #333;
  }

  .remark-date {
    font-size: 3vw;
    color: #999;
  }

  /* 评论操作按钮 */
  .remark-actions {
    display: flex;
    gap: 1vw;
  }

  .remark-actions button {
    display: flex;
    align-items: center;
    gap: 0.5vw;
    padding: 1vw 2vw;
    border: none;
    border-radius: 4px;
    font-size: 3vw;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .btn-delete {
    background-color: #ff4757;
    color: white;
  }

  .btn-delete:hover:not(:disabled) {
    background-color: #ff6b81;
  }

  .btn-edit {
    background-color: #2ed573;
    color: white;
  }

  .btn-edit:hover {
    background-color: #7bed9f;
  }

  .btn-delete:disabled,
  .btn-edit:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  .btn-text {
    font-size: 2.8vw;
  }

  /* 评论内容 */
  .remark-content {
    padding-left: 12vw;
  }

  .remark-content p {
    font-size: 3.8vw;
    color: #333;
    line-height: 1.5;
    margin: 0;
  }

  /* 编辑模式 */
  .edit-mode textarea {
    width: 100%;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 2vw;
    font-size: 3.8vw;
    resize: vertical;
    min-height: 20vw;
  }

  .edit-actions {
    display: flex;
    gap: 2vw;
    margin-top: 2vw;
  }

  .btn-save {
    background-color: #0097FF;
    color: white;
    border: none;
    padding: 1.5vw 3vw;
    border-radius: 4px;
    cursor: pointer;
  }

  .btn-save:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  .btn-cancel {
    background-color: #95a5a6;
    color: white;
    border: none;
    padding: 1.5vw 3vw;
    border-radius: 4px;
    cursor: pointer;
  }

  /* 无评论提示 */
  .no-remarks {
    text-align: center;
    padding: 10vw;
    color: #999;
    font-size: 4vw;
  }

  .no-remarks i {
    font-size: 10vw;
    margin-bottom: 3vw;
    display: block;
  }

  /* 评论输入框 */
  .remark-input {
    position: fixed;
    bottom: 14vw;
    left: 0;
    width: 100%;
    height: 12vw;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 3vw;
    box-sizing: border-box;
    border-top: 1px solid #eee;
  }

  .remark-input input {
    flex: 1;
    height: 8vw;
    border: 1px solid #ddd;
    border-radius: 4vw;
    padding: 0 3vw;
    font-size: 3.8vw;
    outline: none;
  }

  .remark-input button {
    width: 20vw;
    height: 8vw;
    margin-left: 2vw;
    background-color: #0097FF;
    color: #fff;
    border: none;
    border-radius: 4vw;
    font-size: 3.5vw;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1vw;
  }

  .remark-input button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  /* 模态框样式 */
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
  }

  .modal-content {
    background-color: white;
    border-radius: 8px;
    width: 80%;
    max-width: 400px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 3vw;
    border-bottom: 1px solid #eee;
  }

  .modal-header h3 {
    margin: 0;
    font-size: 4vw;
    color: #333;
  }

  .modal-header .fa-times {
    font-size: 4vw;
    color: #999;
    cursor: pointer;
  }

  .modal-body {
    padding: 4vw;
  }

  .modal-body p {
    margin: 0;
    font-size: 3.8vw;
    color: #666;
  }

  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 2vw;
    padding: 3vw;
    border-top: 1px solid #eee;
  }

  .modal-footer button {
    padding: 2vw 4vw;
    border: none;
    border-radius: 4px;
    font-size: 3.5vw;
    cursor: pointer;
  }

  .btn-confirm {
    background-color: #ff4757;
    color: white;
  }

  .btn-confirm:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }

  .btn-cancel {
    background-color: #95a5a6;
    color: white;
  }
</style>